/*
 * Copyright 2011 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.core.utils
{

	public class Formatter
	{

		private static const HOLDER_PATTERN:RegExp = /\{([^}]+)\}/;

		private var _tokens:Vector.<Token>;

		public function Formatter(pattern:String)
		{
			compile(pattern);
		}

		public function format(args:Object):String
		{
			if (_tokens === null)
			{
				return "";
			}

			var result:String = "";
			var token:Token;
			var value:Object;
			var i:uint, len:uint;

			for (i = 0, len = _tokens.length; i < len; i++)
			{
				token = _tokens[i];
				if (token.type === 1)
				{
					if (args === null)
					{
						value = "";
					}
					else
					{
						value = args[token.key];
						if (value === null)
						{
							value = "";
						}
					}

					result += value;
				}
				else
				{
					result += token.str;
				}
			}

			return result;
		}

		private function compile(pattern:String):void
		{
			if (pattern === null)
			{
				return;
			}

			var tokens:Array = [];
			var idx:int, i:int;
			var match:Array, token:String;

			while (true)
			{
				match = pattern.match(HOLDER_PATTERN);
				if (match === null)
				{
					break;
				}

				idx = match.index;
				token = match[1];
				if (idx > 0)
				{
					tokens[i++] = new Token(null, pattern.substring(0, idx), 0);
				}
				tokens[i++] = new Token(token, null, 1);
				pattern = pattern.substring(idx + token.length + 2);

				if (pattern === "")
				{
					break;
				}
			}

			if (pattern !== "")
			{
				tokens[i++] = new Token(null, pattern, 0);
			}

			_tokens = Vector.<Token>(tokens);
		}
	}
}

import sweezy.core.utils.StringUtils;

class Token
{

	public var end:uint;

	public var key:String;

	public var start:uint = 0;

	public var str:String;

	public var type:int;

	public function Token(key:String, str:String, type:int)
	{
		if (type === 1)
		{
			processKey(key);
		}
		else
		{
			this.str = str;
		}

		this.type = type;
	}

	private function processKey(key:String):void
	{
		var tokens:Array = key.split(":");

		this.key = StringUtils.trim(tokens[0]);

		if (tokens.length > 1)
		{
			start = int(StringUtils.trim(tokens[1]));
		}
		if (tokens.length > 2)
		{
			end = int(StringUtils.trim(tokens[2]));
		}
	}
}
